package liuliu.throughwaring.control.task;

import android.content.Context;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;

import net.tsz.afinal.FinalDb;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import liuliu.custom.method.Utils;
import liuliu.custom.model.Cryptography;
import liuliu.throughwaring.control.main.IMainView;
import liuliu.throughwaring.control.net.DBHelper;
import liuliu.throughwaring.control.net.HttpTask;
import liuliu.throughwaring.control.picture.IPictureView;
import liuliu.throughwaring.control.settting.ISettingView;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.InvokeReturn;
import liuliu.throughwaring.model.Key;
import liuliu.throughwaring.model.ModifiedModel;
import liuliu.throughwaring.model.NationAlarmModel;
import liuliu.throughwaring.model.NoticeModel;
import liuliu.throughwaring.model.PersonModel;
import liuliu.throughwaring.model.PoliceModel;
import liuliu.throughwaring.model.TerminalModel;


/**
 * Created by Administrator on 2015/11/13.
 */
public class QueryTask {
    Context mContext;
    FinalDb db;
    HttpTask task;
    ISettingView iSettingView;
    IMainView iMainView;
    int count = 1;
    DBHelper dbHelper;

    public QueryTask(Context context) {
        mContext = context;
        db = FinalDb.create(context);
        task = new HttpTask(mContext);
    }

    boolean isTrue = true;

    public void getPersons() {
        task = new HttpTask(mContext);
        isTrue = true;
        task.start("GetPersons", "", "PersonModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, final InvokeReturn invokeReturn) {
                count++;
                if (result) {
                    if (invokeReturn.isSuccess()) {
                        //System.out.println("下载人员信息成功");
                        final List<CompanyModel> list = db.findAll(CompanyModel.class);
                        DBHelper.DBHelperListener dbHelperListener = new DBHelper.DBHelperListener() {
                            @Override
                            public void dbHelper() {
                                for (Object o : invokeReturn.getData()) {
                                    PersonModel p = (PersonModel) o;
                                    p.setPersonChangeTime(Utils.getDateString(p.getPersonChangeTime()));
                                    p.setPersonCreateTime(Utils.getDateString(p.getPersonCreateTime()));
                                    p.setCheckInTime(Utils.getDateString(p.getCheckInTime()));
                                    p.setCheckOutTime(Utils.getDateString(p.getCheckOutTime()));
                                    final List<CompanyModel> coms = db.findAllByWhere(CompanyModel.class, " CompanyId='" + p.getPersonCompanyId() + "'");
                                    if (coms.size() > 0) {
                                        p.setPersonComapnyName(coms.get(0).getCompanyName());
                                        p.setPersonComapnyType(coms.get(0).getCompanyType());
                                    }
                                    db.save(p);
                                }
                            }

                            @Override
                            public void dbHelperResult() {
                            }
                        };
                        dbHelper = new DBHelper(db, dbHelperListener);
                        dbHelper.start();
                    } else {
                        if (iSettingView != null) {
                            isTrue = false;
                            iSettingView.downLoad(false, "下载人员信息失败:" + invokeReturn.getMessage());
                        }
                        task = null;
                    }
                } else {
                    if (iSettingView != null) {
                        isTrue = false;
                        iSettingView.downLoad(false, "下载人员信息失败");
                    }
                    task = null;
                }
            }
        });
        if (isTrue) {
            if (iSettingView != null) {
                iSettingView.downLoad(true, "更新数据成功");
            }
        }
    }

    /**
     * 获取字典信息
     */
    public void getCode() {
        task = new HttpTask(mContext);
        task.start("GetCode", "", "CodeModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, final InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            if (invokeReturn.getData().size() > 0) {
                                DBHelper.DBHelperListener dbHelperListener = new DBHelper.DBHelperListener() {
                                    @Override
                                    public void dbHelper() {
                                        int i = 0;
                                        for (Object o : invokeReturn.getData()) {
                                            CodeModel codeModel = (CodeModel) o;
                                            //查询本地数据库是否有记录，有则修改，没有则添加
                                            List<CodeModel> list = db.findAllByWhere(CodeModel.class, "codeName='" + invokeReturn.getMessage() + "' and Name='" + codeModel.getName() + "' and Value='" + codeModel.getValue() + "'");
                                            codeModel.setCodeName(invokeReturn.getMessage());
                                            if (list.size() > 0) {
                                                codeModel.setId(list.get(0).getId());
                                                db.update(codeModel);
                                            } else {
                                                codeModel.setId(invokeReturn.getMessage() + i);
                                                db.save(codeModel);
                                            }
                                            i++;
                                        }
                                    }

                                    @Override
                                    public void dbHelperResult() {
                                        if (Utils.ReadString("CodeName").equals(invokeReturn.getMessage())) {
                                            getCompanies();
                                        }
                                        System.out.println(Utils.ReadString("CodeName") + ":::" + invokeReturn.getMessage());
                                    }
                                };
                                dbHelper = new DBHelper(db, dbHelperListener);
                                dbHelper.start();
                            }
                        } else {
                            if (iSettingView != null) {
                                iSettingView.downLoad(false, "字典下载：" + invokeReturn.getMessage());
                            }
                            task = null;
                        }
                    } else {
                        if (iSettingView != null) {
                            iSettingView.downLoad(false, "字典下载网络出错");
                            System.out.println("字典下载网络出错");
                        }

                        task = null;
                    }
                } else {
                    if (iSettingView != null) {
                        iSettingView.downLoad(false, "字典下载网络出错");
                        System.out.println("字典下载网络出错");
                    }
                    task = null;
                }
            }
        });
    }

    /**
     * 获得全国犯罪人员库信息
     */
    public void getNationAlarm(ISettingView iv) {
        iSettingView = iv;
        task = new HttpTask(mContext);
        task.start("GetNationAlarm", "", "NationAlarmModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, final InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        DBHelper.DBHelperListener dbHelperListener = new DBHelper.DBHelperListener() {
                            @Override
                            public void dbHelper() {
                                db.deleteAll(NationAlarmModel.class);
                                for (int i = 0; i < invokeReturn.getData().size(); i++) {
                                    NationAlarmModel nationAlarmModel = (NationAlarmModel) invokeReturn.getData().get(i);
                                    db.save(nationAlarmModel);
                                }
                            }

                            @Override
                            public void dbHelperResult() {
                                if (null != iSettingView) {
                                    iSettingView.DownKu(true);
                                }
                            }
                        };
                        dbHelper = new DBHelper(db, dbHelperListener);
                        dbHelper.start();
                    } else {
                        if (null != iSettingView) {
                            iSettingView.DownKu(false);
                        }
                    }
                } else {
                    if (null != iSettingView) {
                        iSettingView.DownKu(false);
                    }
                }
            }
        });
    }

    /**
     * 修改密码
     */
    public void modifyPassword(final String newPsw, final ISettingView iSettingView) {
        task = new HttpTask(mContext);
        task.start("ChangePassword", "NewPassword=" + Utils.URLEncode(newPsw), "", new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            //System.out.println("修改密码成功");
                            iSettingView.downLoad(true, "修改密码成功");
                            //修改成功后将新密码保存到数据库
                            List<TerminalModel> models = db.findAll(TerminalModel.class);
                            TerminalModel terminalModel = models.get(0);
                            try {
                                terminalModel.setTerminalPassword(Cryptography.hashPassword(newPsw));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            } catch (NoSuchAlgorithmException e) {
                                e.printStackTrace();
                            }
                            db.update(terminalModel);
                        } else {
                            //错误提示信息
                            iSettingView.downLoad(true, "修改密码失败：" + invokeReturn.getMessage());
                            //System.out.println("修改密码:" + invokeReturn.getMessage());
                        }
                    }
                } else {
                    iSettingView.downLoad(true, "修改密码失败");
                    //System.out.println("修改密码失败");
                }
            }
        });
    }

    /**
     * 下载本辖区所有企业信息
     */
    public void getCompanies() {
        task = new HttpTask(mContext);
        task.start("GetCompanies", "", "CompanyModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, final InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            System.out.println("企业信息下载成功");
                            //清空所有企业信息
                            DBHelper.DBHelperListener dbHelperListener = new DBHelper.DBHelperListener() {
                                @Override
                                public void dbHelper() {
                                    db.deleteAll(CompanyModel.class);
                                    for (Object o : invokeReturn.getData()) {
                                        CompanyModel companyModel = (CompanyModel) o;
                                        companyModel.setCompanyChangeTime(Utils.getDateString(companyModel.getCompanyChangeTime()));
                                        companyModel.setCompanyCreateTime(Utils.getDateString(companyModel.getCompanyCreateTime()));
                                        DPoint dPoint = baiduZhuanGaode(companyModel.getCompanyEastPoint(), companyModel.getCompanyNorthPoint());
                                        companyModel.setCompanyEastPoint(dPoint.getLongitude() + "");
                                        companyModel.setCompanyNorthPoint(dPoint.getLatitude() + "");
//                                        companyModel.setId(i + "");
                                        db.save(companyModel);
                                    }
                                    //修改成功后将新密码保存到数据库
                                    //TerminalModel terminalModel=new TerminalModel();
                                    //db.update(terminalModel);
                                }

                                @Override
                                public void dbHelperResult() {
                                    getPersons();
                                }
                            };
                            dbHelper = new DBHelper(db, dbHelperListener);
                            dbHelper.start();

                        } else {
                            //错误提示信息
                            if (iSettingView != null) {
                                iSettingView.downLoad(false, "企业信息下载:" + invokeReturn.getMessage());
                            }

                            System.out.println("企业信息下载:" + invokeReturn.getMessage());
                            task = null;
                        }
                    } else {
                        if (iSettingView != null) {
                            iSettingView.downLoad(false, "企业信息网络出错");
                        }


                        task = null;
                    }
                } else {
                    if (iSettingView != null) {
                        iSettingView.downLoad(false, "企业信息网络出错");
                    }


                    task = null;
                }
            }
        });
    }

    /**
     * 获取本辖区内所有民警信息
     */
    public void getPolices(final IMainView iMainView) {
        task = new HttpTask(mContext);
        this.iMainView = iMainView;
        task.start("GetPolices", "", "PoliceModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, final InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            DBHelper.DBHelperListener dbHelperListener = new DBHelper.DBHelperListener() {
                                @Override
                                public void dbHelper() {
                                    //清空所有民警信息
                                    db.deleteAll(PoliceModel.class);
                                    for (Object o : invokeReturn.getData()) {
                                        PoliceModel policeModel = (PoliceModel) o;
                                        policeModel.setPoliceCreateTime(Utils.getDateString(policeModel.getPoliceCreateTime()));
                                        policeModel.setPoliceChangeTime(Utils.getDateString(policeModel.getPoliceChangeTime()));
                                        db.save(policeModel);
                                    }
                                }

                                @Override
                                public void dbHelperResult() {

                                }
                            };
                            dbHelper = new DBHelper(db, dbHelperListener);
                            dbHelper.start();
                            String changeTime = Utils.ReadString("CodeChangeTime");
                            if (changeTime.equals("")) {
                                getCode();
                                Utils.WriteString("CodeChangeTime", "1990-01-01 00:00:00");
                            } else {
                                getModified();
                            }
                        } else {
                            //错误提示信息
                            if (iSettingView != null) {
                                iSettingView.downLoad(false, "民警信息下载:" + invokeReturn.getMessage());
                                System.out.println("民警信息下载:" + invokeReturn.getMessage());
                            }

                            task = null;
                        }
                    } else {
                        if (iSettingView != null) {
                            iSettingView.downLoad(false, "民警信息下载失败");
                            System.out.println("民警信息下载失败");
                        }


                        task = null;
                    }
                } else {
                    if (iSettingView != null) {
                        iSettingView.downLoad(false, "民警信息下载失败");
                        System.out.println("民警信息下载失败");
                    }
                    task = null;
                }
            }
        });
    }

    /**
     * 获取未下载的通知通告
     */
    public void getNotice() {
        //检查最后一个消息的时间
        String lastTime = "1990-01-01 00:00:00";
        String time;
        List<NoticeModel> list = db.findAllByWhere(NoticeModel.class, " 1=1 order by NoticeCreateTime desc");
        if (list.size() > 0) {
            time = list.get(0).getNoticeCreateTime();
        } else {
            time = lastTime;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = formatter.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        lastTime = Utils.getDateString(String.valueOf(date.getTime() + 1000));
        task.start("GetNotices", "LastModified=" + lastTime, "NoticeModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            System.out.println("民警信息下载成功");
                            //清空所有民警信息
                            for (Object o : invokeReturn.getData()) {
                                NoticeModel noticeModel = (NoticeModel) o;
                                noticeModel.setNoticeCreateTime(Utils.getDateString(noticeModel.getNoticeCreateTime()));
                                db.save(noticeModel);
                            }
                            //修改成功后将新密码保存到数据库
                            //TerminalModel terminalModel=new TerminalModel();
                            //db.update(terminalModel);
                        } else {
                            //错误提示信息
                            System.out.println("民警信息下载:" + invokeReturn.getMessage());
                        }
                    }
                } else {
                    System.out.println("民警信息下载失败");
                }
            }
        });

    }

    /**
     * 获取设备信息,imei注册设备
     */
    public void getTerminal(final ISettingView iSettingView) {
        task = new HttpTask(mContext);
        this.iSettingView = iSettingView;
        task.start("GetTerminal", "IMEI=" + Utils.getImei(mContext), "TerminalModel", new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            if (invokeReturn.getData().size() > 0) {
                                TerminalModel terminalModel = (TerminalModel) invokeReturn.getData().get(0);
                                // terminalModel.setTerminalPassword(Cryptography.DecryptString(terminalModel.getTerminalPassword()));
                                //查询本地数据库是否有记录，有则修改，没有则添加
                                List<TerminalModel> list = db.findAllByWhere(TerminalModel.class, "TerminalCode='" + Utils.getImei(mContext) + "'");
                                terminalModel.setTerminalChangeTime(Utils.getDateString(terminalModel.getTerminalChangeTime()));
                                terminalModel.setTerminalCreateTime(Utils.getDateString(terminalModel.getTerminalCreateTime()));
                                if (list.size() > 0) {
                                    terminalModel.setId(list.get(0).getId());
                                    db.update(terminalModel);
                                } else {
                                    db.save(terminalModel);
                                }
                                getPolices(null);
                            } else {
                                if (iSettingView != null) {
                                    iSettingView.downLoad(false, invokeReturn.getMessage());
                                }
                            }
                        } else {
                            if (iSettingView != null) {
                                iSettingView.downLoad(false, "GetTerminal网络出错");
                                System.out.println("网络出错1");
                            }
                        }
                    } else {
                        if (iSettingView != null) {
                            iSettingView.downLoad(false, "GetTerminal网络出错");
                            System.out.println("网络出错2");
                            task = null;
                        }
                    }
                } else {
                    if (iSettingView != null) {
                        iSettingView.downLoad(false, "GetTerminal网络出错");
                        System.out.println("网络出错3");
                    }
                }
            }
        });
    }

    public void getModified() {
        task = new HttpTask(mContext);
        task.start("GetModified", "ModifiedName=Sys_Code", "ModifiedModel", new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn.isSuccess()) {
                        //保存本次变更时间，下次先对比时间，是否需要更新
                        System.out.println("modeif请求成功！");
                        if (invokeReturn.getData().size() > 0) {
                            ModifiedModel modifiedModel = (ModifiedModel) invokeReturn.getData().get(0);
                            modifiedModel.setModifiedTime(Utils.getDateString(modifiedModel.getModifiedTime()));
                            String changeTime = Utils.ReadString("CodeChangeTime");

                            if (changeTime.equals("")) {
                                changeTime = "1990-01-01 00:00:00";
                            }
                            Date changeDate = Utils.StringToDate(changeTime);
                            Date changeDate1 = Utils.StringToDate(modifiedModel.getModifiedTime());
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                            Calendar c1 = Calendar.getInstance();
                            Calendar c2 = Calendar.getInstance();
                            c1.setTime(changeDate);
                            c2.setTime(changeDate1);
                            int timeResult = c1.compareTo(c2);
                            if (timeResult < 0) {
                                getCode();
                            } else {
                                getCompanies();
                            }

                            Utils.WriteString("CodeChangeTime", modifiedModel.getModifiedTime());
                            db.deleteAll(ModifiedModel.class);
                            db.save(modifiedModel);
                        } else {
                            getCompanies();
                        }
                    } else {
                        if (iSettingView != null) {
                            iSettingView.downLoad(false, "变更信息下载:" + invokeReturn.getMessage());
                        }

                        System.out.println(invokeReturn.getMessage());
                        task = null;
                    }
                } else {
                    if (iSettingView != null) {
                        iSettingView.downLoad(false, "变更信息,网络错误");
                    }
                    task = null;
                    System.out.println("网络错误");
                }
            }
        });
    }

    public void getHelp(final IMainView iMainView) {
        task = new HttpTask(mContext);
        this.iMainView = iMainView;
        task.start("GetTerimials", "", "TerminalModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                List<PoliceModel> allList = new ArrayList<PoliceModel>();
                if (result) {
                    if (invokeReturn.getData().size() > 0) {
                        for (int i = 0; i < invokeReturn.getData().size(); i++) {
                            TerminalModel terminalModel = (TerminalModel) invokeReturn.getData().get(i);
                            List<PoliceModel> list = db.findAllByWhere(PoliceModel.class, "PoliceId='" + terminalModel.getPoliceId() + "'");
                            if (list.size() > 0) {
                                float JULI = getJuLi(terminalModel.getTerminalEastPoint(), terminalModel.getTerminalNorthPoint());
                                PoliceModel policeModel = list.get(0);
                                policeModel.setPoliceComment(JULI + "");
                                allList.add(list.get(0));
                            }
                        }
                        iMainView.onMainRefreshResult(true, allList);
                    } else {
                        iMainView.onMainRefreshResult(false, null);
                    }
                } else {
                    iMainView.onMainRefreshResult(false, null);
                }
            }
        });
    }

    //根据图片id获取图片
    public void getPicture(String pid, final IPictureView iPictureView) {
        task = new HttpTask(mContext);
        task.start("GetImage", "ImageId=" + pid, "", new
                HttpTask.TaskListener() {
                    @Override
                    public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                        if (result) {
                            if (iPictureView != null) {
                                String mes = invokeReturn.getMessage();
                                if (null == mes) {
                                    iPictureView.PictureResult(false, null);
                                } else {
                                    if (mes.endsWith("&"))
                                        mes = mes.substring(0, mes.length() - 1);

                                    if (!Utils.isEmptyString(mes))
                                        mes += "&rand=" + System.currentTimeMillis();
                                    String ip = Utils.ReadString(Key.KEY_IP);
                                    String port = Utils.ReadString(Key.KEY_PORT);
                                    String url = ip + ":" + port;
                                    String mUrl = String.format("http://%s%s", url, mes);
                                    iPictureView.PictureResult(true, mUrl);
                                }
                            }
                            System.out.println("图片加载成功");
                        } else {
                            System.out.println("图片加载失败");
                        }
                    }
                });
    }


    //计算两点之间的距离
    private float getJuLi(String eastPoint, String northPoint) {
        String Latitude = Utils.ReadString("Latitude");
        String Longitud = Utils.ReadString("Longitud");
        if (Latitude.equals("")) {
            Latitude = "000.000";
        }
        if (Longitud.equals("")) {
            Longitud = "000.000";
        }
        LatLng start = new LatLng(Double.parseDouble(Latitude), Double.parseDouble(Longitud));
        //转化坐标

//        eastPoint="23.369";
//        northPoint="23.254";
        LatLng end = null;
        float mi = 0;
        DPoint newPoint = baiduZhuanGaode(eastPoint, northPoint);
        if (null != newPoint) {
            end = new LatLng(newPoint.getLatitude(), newPoint.getLongitude());
            mi = AMapUtils.calculateLineDistance(start, end);
            return mi;
        }
        return 0;
    }

    //转换坐标
    private DPoint baiduZhuanGaode(String eastPoint, String northPoint) {
        DPoint newPoint = null;
        CoordinateConverter converter = new CoordinateConverter(mContext);
        converter.from(CoordinateConverter.CoordType.BAIDU);
        if (eastPoint.equals("") || northPoint.equals("")) {
            System.out.println("kong notice;;;");
        } else {
            Double longitud = Double.parseDouble(eastPoint);
            Double latitude = Double.parseDouble(northPoint);
            DPoint point = new DPoint();
            point.setLatitude(latitude);
            point.setLongitude(longitud);


            try {
                converter.coord(point);
                newPoint = converter.convert();
            } catch (Exception ex) {
                //System.out.println("坐标转化失败");

            }

        }
        return newPoint;
    }


}

